package wwl.lsf.hellospringboot.鲁班.并发;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CLHLock {

  public static class CLHNode {

    private volatile boolean isWaiting = true; // 默认是在等待锁
  }

  private volatile CLHNode tail;
  private static final AtomicReferenceFieldUpdater<CLHLock, CLHNode> UPDATER = AtomicReferenceFieldUpdater
      .newUpdater(CLHLock.class, CLHNode.class, "tail");

  public void lock(CLHNode currentThread) {
    CLHNode preNode = UPDATER.getAndSet(this, currentThread);
    if (preNode != null) {//已有线程占用了锁，进入自旋
      while (preNode.isWaiting) {
      }
    }
  }

  public void unlock(CLHNode currentThread) {
    // 如果队列里只有当前线程，则释放对当前线程的引用（for GC）。
    if (!UPDATER.compareAndSet(this, currentThread, null)) {
      // 还有后续线程
      currentThread.isWaiting = false;// 改变状态，让后续线程结束自旋
    }
  }

  public static void main(String[] args) {

    AtomicReference<String> atomicReference = new AtomicReference<>();
    atomicReference.getAndSet("wwl");
    Lock lock=new ReentrantLock();

  }
}